# -*- coding: utf-8 -*-
"""
Created on Sat Apr 15 15:15:25 2017

@author: GangTimes
"""
#相关包导入
import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.font_manager as fm

#绘图设置
zh_font=fm.FontProperties(fname=r"c:\windows\fonts\simsun.ttf",size=18)#路径用小写  大写不行 有这个不能保存为eps
en_font=fm.FontProperties(family='monospace',size=18)
zf_font=fm.FontProperties(family='Times New Roman',style='italic',size=16)

fig1=plt.figure(figsize=(7,5))
ax1=Axes3D(fig1,[0,0,1,1])
ax1.set_xlabel('x',fontproperties=zf_font)
ax1.set_ylabel('y',fontproperties=zf_font)
ax1.set_ylabel('z',fontproperties=zf_font)

fig2=plt.figure(figsize=(7,5))
ax2=Axes3D(fig2,[0,0,1,1])
ax2.set_xlabel('x',fontproperties=zf_font)
ax2.set_ylabel('y',fontproperties=zf_font)
ax2.set_ylabel('z',fontproperties=zf_font)
#全局变量
x_start=-10
y_start=-10
x_end=10
y_end=10
num=50
mesh_num=100j

def linear_model(theta,x,y):
    '''
    通过输入的模型参数和自变量 计算线性模型的输出
    模型参数 theta: matrix[3x1] 
    自变量 x y    : matrix[nx1  nxn] n为样本数
    '''
    a=theta[0,0]
    b=theta[1,0]
    c=theta[2,0]
    		
    return a*x+b*y+c

def self_surf(xm,ym,zm,ax):
    	'''
    	通过输入的点 绘制云图
    	'''
    	ax.plot_surface(xm,ym,zm,rstride=1,cstride=1,cmap=plt.cm.hsv,linestyles='dashdot',linewidth=0.5,alpha=0.3)

def self_plot3(xr,yr,zr,ax):
    '''
    绘制散点图
    xr yr zr:matrix[nx1]
    '''
    x=xr.A1
    y=yr.A1
    z=zr.A1
    ax.scatter(x,y,z,c='g',marker='^',s=48)
    
def create_data():
    theta=numpy.matrix([[2],[3],[4]])
    xm,ym=numpy.mgrid[x_start:x_end:mesh_num,y_start:y_end:mesh_num]
    zm=linear_model(theta,xm,ym)
    self_surf(xm,ym,zm,ax1)
    
    xr=numpy.matrix(20*numpy.random.random(size=num)-10).T
    yr=numpy.matrix(20*numpy.random.random(size=num)-10).T
    zr=linear_model(theta,xr,yr)+numpy.matrix(numpy.random.normal(0,1,[num,1]))
    print(xr)
    print(zr)
    self_plot3(xr,yr,zr,ax1)
    
    cone=numpy.matrix(numpy.ones((num,1)))
   
    X=numpy.hstack((xr,yr,cone))
    Y=zr
    
    return [X,Y] 

def linear_main():
    [X,Y]=create_data()
    theta=(X.T*X).I*X.T*Y
          
    xm,ym=numpy.mgrid[x_start:x_end:mesh_num,y_start:y_end:mesh_num]
    zm=linear_model(theta,xm,ym)
    self_surf(xm,ym,zm,ax2)
    self_plot3(X[:,0],X[:,1],Y,ax2)
    plt.show()
    
if __name__=='__main__':
    linear_main()